import { reload_col, obj_str, d_sort, loc, cline, is_empty, uDb } from 'sui';
import { fix_psn } from '../cmd';
import { psn_mod } from 'tech/cmd';

const reload = (hDone, setMain, cur) => {
    uDb(hDone, "psn/list",
        {
            line: cline(),
            k: obj_str(cur, "sn"),
        },
        data => {
            if (is_empty(data)) {
                setMain(null);
                return;
            }

            d_sort(data, "sn");

            data.forEach((d, i) => d["index"] = i + 1);

            setMain(data);
        }, e => setMain(null));
};

const do_md = (umd, setMain, s, e, v, hcmd) => {
    umd.startWait();

    uDb(null, "task/md",
        {
            line: cline(),
            k: obj_str(v, "sn"),
            v: v,
        },
        r => {
            reload(umd.endWait, setMain, s, e);

            if (hcmd) {
                hcmd();
            }
        }, e => umd.setErr(loc("l_232")), true);
};

const do_add = (umd, setMain, s, e, v, hcmd) => {
    umd.startWait();

    uDb(null, "task/add",
        {
            line: cline(),
            v: v,
        },
        r => {
            reload(umd.endWait, setMain, s, e);

            if (hcmd) {
                hcmd();
            }
        }, e => umd.setErr(loc("l_232")), true);
};

const load_col_psn = (setCol, fix_col, cur) => {
    const set = new Set();
    const fix = fix_psn();

    fix.forEach(d => set.add(d.sn));

    if (fix_col) {
        fix_col.forEach(d => {
            if (set.has(d.sn)) {
                return;
            }

            fix.push(d);
            set.add(d.sn);
        });
    }

    const mod = psn_mod(obj_str(cur, "tp"));

    reload_col(null, v => setCol(v), mod, fix);
};

export {load_col_psn, do_add, do_md, reload};
